import axios from 'axios';

// 请求拦截器
axios.interceptors.request.use(
  
  config => {

    const userInfo = JSON.parse(localStorage.getItem('userInfo')) || {};

    const adminName = userInfo.userName || '';
    const adminToken = userInfo.token || '';

    if (adminName && adminToken &&  adminName === 'admin') {

      config.headers.userName = adminName;
      config.headers.token = adminToken;
    }

    config.url = '/api' + config.url;

    return config;
  },

  err => Promise.reject(err)
)

// 添加响应拦截器
axios.interceptors.response.use(
  // 响应成功时
  res => {
    return res.data
  },

  err => Promise.reject(err)
)

export const request = (url, data = {}, method = "get") => {
  
  return new Promise((resolve, reject) => {

    let promise;

    if (method === "get") {
      promise = axios.get(`${url}?v=${Date.now()}`, { params: data });
    } else if (method === "post") {
      promise = axios.post(`${url}?v=${Date.now()}`, data);
    }

    promise
      .then(res => resolve(res))
      .catch(err => reject(err))
  })
}